package ru.ipccenter.jshell.backend.server;

import java.util.logging.Logger;

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;

public class StdInOutConfigurator extends ServerEndpointConfig.Configurator {

  private static final Logger LOG = Logger.getLogger(StdInOutConfigurator.class.getName());
  private HttpSession httpSession;
  
  @Override
  public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
    
      httpSession = (HttpSession) request.getHttpSession();
      super.modifyHandshake(sec, request, response);
  }
  
  @Override
  public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {

      T endpoint = super.getEndpointInstance(endpointClass);

      if (endpoint instanceof StdInOutEndpoint) {
        ((StdInOutEndpoint) endpoint).setHttpSession(httpSession);
      } else {
        LOG.severe("Expected instanceof " + StdInOutEndpoint.class + ", but got " + endpoint.getClass());
        throw new InstantiationException(
                  "Expected instanceof " + StdInOutEndpoint.class + ", but got " + endpoint.getClass());
      }
      return endpoint;
  }
}
